<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: 当燃 2016-01-09
 */ 
namespace Mobile\Controller;
require_once 'vendor/autoload.php';
require_once "wxpayv3/WxPay.Api.php";
require_once "wxpayv3/WxPay.Data.php";
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: *');

use Common\Model\GoodsModel;
use Mobile\Model\StoreModel;
use TencentCloud\Sms\V20210111\SmsClient;
// 导入要请求接口对应的Request类
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use Pay\Controller\PayController;


class IndexController extends MobileBaseController {

    public function index(){                
        /*
            //获取微信配置
            $wechat_list = M('wx_user')->select();
            $wechat_config = $wechat_list[0];
            $this->weixin_config = $wechat_config;        
            // 微信Jssdk 操作类 用分享朋友圈 JS            
            $jssdk = new \Mobile\Logic\Jssdk($this->weixin_config['appid'], $this->weixin_config['appsecret']);
            $signPackage = $jssdk->GetSignPackage();              
            print_r($signPackage);
        */
        $hot_goods = M('goods')->where("is_hot=1 and is_on_sale=1")->order('goods_id DESC')->limit(20)->cache(true,TPSHOP_CACHE_TIME)->select();//首页热卖商品
        $thems = M('goods_category')->where('level=1')->order('sort_order')->limit(9)->cache(true,TPSHOP_CACHE_TIME)->select();
        $this->assign('thems',$thems);
        $this->assign('hot_goods',$hot_goods);
        $favourite_goods = M('goods')->where("is_recommend=1 and is_on_sale=1")->order('goods_id DESC')->limit(20)->cache(true,TPSHOP_CACHE_TIME)->select();//首页推荐商品
        $this->assign('favourite_goods',$favourite_goods);
        $this->display();
    }
    function tuikuan(){
    $goods_id=I('goods_id');
    
    $id=I('uid');
    $code=I('code');
    $appId = 'wxa1033a5ac7c90c3d'; // 替换为您的 App ID
    $appSecret = '3687777d26641531f21168a389df485f'; // 替换为您的 App Secret
  
    // 构造接口请求 URL
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" .$appId. "&secret=".$appSecret."&code=". $code."&grant_type=authorization_code";
    
    // 发起 HTTP 请求获取结果
    $response = file_get_contents($url);

  
    // 解析 JSON 格式的响应结果
    $result = json_decode($response, true);
    //var_dump($id);
   $good=M('goods')->where("goods_id={$goods_id}")->find();
    $data=array();
    $data['store_id']=$id;
    $data['create_time']=time();
    $data['money']=$good['shop_price']*$good['store_count'];
    $data['bank_name']='微信';
    $data['account_name']=$result['openid'];
    $data['goods_id']=$goods_id;
    $data['goods_name']=$good['goods_name'];
    M('store_withdrawals')->add($data);
    $data=array();
    $data['is_on_sale']=0;
    M('goods')->where("goods_id={$id}")->save($data);
    $data=array();
    $data['status']=200;
   
    echo json_encode($data); 
    }
    function faduanxin(){
        //var_dump(I('phone'));die();
        $phone=I('phone');
        $code=rand(111111,999999);
        $cred = new Credential("AKIDXyIWeeP0Vr4vZzKTQ8anlW4PVP4XgcOA", "kJpCLGwQhlbTGwYyBJRSKJ90y471oaKw");
        //$cred = new Credential(getenv("TENCENTCLOUD_SECRET_ID"), getenv("TENCENTCLOUD_SECRET_KEY"));
    
    
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        $httpProfile = new HttpProfile();
        // 配置代理（无需要直接忽略）
        // $httpProfile->setProxy("https://ip:port");
        $httpProfile->setReqMethod("GET");  // post请求(默认为post请求)
        $httpProfile->setReqTimeout(30);    // 请求超时时间，单位为秒(默认60秒)
        $httpProfile->setEndpoint("sms.tencentcloudapi.com");  // 指定接入地域域名(默认就近接入)
    
    
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        $clientProfile = new ClientProfile();
        $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法(默认为HmacSHA256)
        $clientProfile->setHttpProfile($httpProfile);
    
    
        // 实例化要请求产品(以sms为例)的client对象,clientProfile是可选的
        // 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);
    
    
        // 实例化一个 sms 发送短信请求对象,每个接口都会对应一个request对象。
        $req = new SendSmsRequest();
    
    
        /* 填充请求参数,这里request对象的成员变量即对应接口的入参
         * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
         * 基本类型的设置:
         * 帮助链接：
         * 短信控制台: https://console.cloud.tencent.com/smsv2
         * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
    
    
        /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
        // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
        $req->SmsSdkAppId = "1400850203";
        /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
        // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
        $req->SignName = "惠界悬赏令App";
        /* 模板 ID: 必须填写已审核通过的模板 ID */
        // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
        $req->TemplateId = "1908946";
        /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空*/
        $req->TemplateParamSet = array($code);
        /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
         * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
        $req->PhoneNumberSet = array("+86".$phone);
        /* 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
        $req->SessionContext = "";
        /* 短信码号扩展号（无需要可忽略）: 默认未开通，如需开通请联系 [腾讯云短信小助手] */
        $req->ExtendCode = "";
        /* 国内短信无需填写该项；国际/港澳台短信已申请独立 SenderId 需要填写该字段，默认使用公共 SenderId，无需填写该字段。注：月度使用量达到指定量级可申请独立 SenderId 使用，详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。*/
        $req->SenderId = "";
    
    
        // 通过client对象调用SendSms方法发起请求。注意请求方法名与请求对象是对应的
        // 返回的resp是一个SendSmsResponse类的实例，与请求对象对应
        $resp = $client->SendSms($req);
    
         $data=array();
         $data['status']=200;
         $data['code']=$code;
         echo json_encode( $data);
        // 输出json格式的字符串回包
      //  print_r($resp->toJsonString());
        
    }
    function addtixian(){
        $error=I('error');
        Think\Log::record($error);   
    }
   function getindex(){
       $ad=M('ad')->where("pid=2")->select();
       $banner=array();
       foreach($ad as $k => $v){
       $ban=array();
       $ban['background']=$v['bgcolor'];
       $ban['link']=$v['ad_link'];
       $ban['src']='http://renwu.tzhtc.net'.$v['ad_code'];
       $banner[]=$ban;
       } 
    
       $is_recommend=M('goods')->where("is_recommend=1")->order("goods_id desc")->limit(100)->select();//是否推荐
       $is_recommend1=M('goods')->where("is_hot=1")->order("goods_id desc")->limit(100)->select();//是否最热
       $fenlei=M('goods_category')->where("parent_id=0")->select();
       $config=array();
       $config['banner']=$banner;
       $config['fenlei']=$fenlei;
       $data=array();
       $data['status']=200;
       $data['config']=$config;
       $data['is_recommend']=$is_recommend;
       $data['is_recommend1']=$is_recommend1;
       echo json_encode($data);
   }
      function getzuidi(){

       $inc_type="renwu_set";
       $renwu_set=tpCache($inc_type);


       $renwu_min_price = $renwu_set["renwu_min_price"];//最小任务单价
       $renwu_min_num = $renwu_set["renwu_min_num"];//最小任务投放数量
       $renwu_min_toplimit = $renwu_set["renwu_min_toplimit"];//最小任务单价



        $config=M('config')->where("id=1")->find();
        $data=array();
        $data['status']=200;
        $data['zprice']=$config['value'];
        $data['renwu_min_price']=$renwu_min_price;
        $data['renwu_min_num']=$renwu_min_num;
        $data['renwu_min_toplimit']=$renwu_min_toplimit;
    
        echo json_encode($data);
   }
   function weilogin(){
        $user= array();
        $code=I('code');
        $appId = 'wxa1033a5ac7c90c3d'; // 替换为您的 App ID
        $appSecret = '3687777d26641531f21168a389df485f'; // 替换为您的 App Secret

        // 构造接口请求 URL
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" .$appId. "&secret=".$appSecret."&code=". $code."&grant_type=authorization_code";
        $response = file_get_contents($url);
        $result = json_decode($response, true);
        $access_token=$result['access_token'];
        $openid=$result['openid'];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid;
        $response = file_get_contents($url);
        // echo $response;
        $data = json_decode($response, true);
        $add=array();
        $add['head_pic']=$data['headimgurl'];
        $add['mobile']="";
        $add['nickname']=$data['nickname'];
        $userInfo = D("users")->where(array("wx_openid"=>$openid))->find();
        if(!empty($userInfo)){
            $add['last_login']=time();//最后登录时间
            $user=M('users')->where("user_id={$userInfo['user_id']}")->find();
        }else{
            $add['reg_time']=time();
            $add["wx_openid"]=$openid;
            $result=M('users')->add($add);
            $user=M('users')->where("user_id={$result}")->find();
        }
        $data=array();
        $data['status']=200;
        $data['userinfo']=$user;
        echo json_encode($data);
   }
   
   function tixian(){
    $id=I('uid');
    $code=I('code');
    $appId = 'wxa1033a5ac7c90c3d'; // 替换为您的 App ID
    $appSecret = '3687777d26641531f21168a389df485f'; // 替换为您的 App Secret
    // 构造接口请求 URL
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" .$appId. "&secret=".$appSecret."&code=". $code."&grant_type=authorization_code";
    // 发起 HTTP 请求获取结果
    $response = file_get_contents($url);
    // 解析 JSON 格式的响应结果
    $result = json_decode($response, true);
    $user=M('users')->where("user_id={$id}")->find();
    if(empty($user)){
        echo json_encode(array("status"=>0,"msg"=>"用户信息错误"));die();
    }
    $openid = $user["wx_openid"];
    $inc_type="withdraw_set";
    $withdraw_set=tpCache($inc_type);
    $data=array();
    $withdraw_outlay =$withdraw_set["withdraw_outlay"];//手续费
    $withdraw_min_money =$withdraw_set["withdraw_min_money"];//最小提现金额
    $withdraw_money =0;
    
    
    if(!empty($withdraw_outlay)){
        $outlay_money = ($user['user_money']*$withdraw_set["withdraw_outlay"])/100;
        $withdraw_money =$user['user_money']- $outlay_money;
        $withdraw_money = sprintf("%.2f", $withdraw_money);
        $data['withdraw_money']=$withdraw_money;
        $data["withdraw_outlay"]=$outlay_money;
    }
    if($user['user_money']-$withdraw_min_money<0){
        echo json_encode(array("status"=>0,"msg"=>"可提现金额小与最低提现金额".$withdraw_min_money."元"));die();
    }
    $data['user_id']=$id;
    $data['create_time']=time();
    $data['money']=$user['user_money'];
    $data['bank_name']='微信';
    $data['account_name']=$result['openid'];
    M('withdrawals')->add($data);
    $data=array();
    $data['user_money']=0;
    M('users')->where("user_id={$id}")->save($data);
    $data=array();
    $data['status']=200;
    
    // $this->tixianjin($openid,$data['withdraw_money']);
    echo json_encode($data);
   }
   
   
   
   function tixianjin($openid,$money){
  
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        //请求方式
        $http_method = 'POST';
        //请求参数
        $data = [
            'appid' =>'wxa1033a5ac7c90c3d',//申请商户号的appid或商户号绑定的appid（企业号corpid即为此appid）
            'out_batch_no' =>rand(1111,9999).time(),//商户系统内部的商家批次单号，要求此参数只能由数字、大小写字母组成，在商户系统内部唯一
            'batch_name' => '提现至微信零钱',//该笔批量转账的名称
            'batch_remark' => '提现至微信零钱',//转账说明，UTF8编码，最多允许32个字符
            'total_amount' => $money * 100,//转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致，否则无法发起转账操作
            'total_num' => 1,//一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致，否则无法发起转账操作
            'transfer_detail_list' => [
                [//发起批量转账的明细列表，最多三千笔
                    'out_detail_no' =>rand(1111,9999).time(),//商户系统内部区分转账批次单下不同转账明细单的唯一标识，要求此参数只能由数字、大小写字母组成
                    'transfer_amount' => $money * 100,//转账金额单位为分
                    'transfer_remark' => '提现至微信零钱',//单条转账备注（微信用户会收到该备注），UTF8编码，最多允许32个字符
                    'openid' =>$openid,//openid是微信用户在公众号appid下的唯一用户标识（appid不同，则获取到的openid就不同），可用于永久标记一个用户
                ]]
        ];
  
 
        $token  = self::token($url,$http_method,$data,$config);//获取token
        $result = self::https_request($url,json_encode($data),$token);//发送请求
        $result_arr = json_decode($result,true);
        var_dump( $result_arr );die();
        if(!isset($result_arr['create_time'])) {//批次受理失败
            throw new \Exception($result_arr['message']);
        }
 
        //批次受理成功，进行操作
 
 
        return true;
   }
   public static function token($url,$http_method,$data,$config)
   {
       $timestamp   = time();//请求时间戳
       $url_parts   = parse_url($url);//获取请求的绝对URL
       $nonce       = $timestamp.rand('10000','99999');//请求随机串
       $body        = empty($data) ? '' : json_encode((object)$data);//请求报文主体
       $stream_opts = [
           "ssl" => [
               "verify_peer"=>false,
               "verify_peer_name"=>false,
           ]
       ];

       $apiclient_cert_arr = openssl_x509_parse(file_get_contents('http://renwu.tzhtc.net/cret/apiclient_cert.pem',false, stream_context_create($stream_opts)));
       $serial_no          = $apiclient_cert_arr['serialNumberHex'];//证书序列号
       $mch_private_key    = file_get_contents('http://renwu.tzhtc.net/cret/apiclient_key.pem',false, stream_context_create($stream_opts));//密钥
       $merchant_id = '1648274388';//商户id
       $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
       $message = $http_method."\n".
           $canonical_url."\n".
           $timestamp."\n".
           $nonce."\n".
           $body."\n";
       openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
       $sign = base64_encode($raw_sign);//签名
       $schema = 'WECHATPAY2-SHA256-RSA2048';
       $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
           $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
       return $schema.' '.$token;
   }

   /**
    * @notes 发送请求
    */
   public static function https_request($url,$data,$token)
   {
       $curl = curl_init();
       curl_setopt($curl, CURLOPT_URL, (string)$url);
       curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
       if (!empty($data)){
           curl_setopt($curl, CURLOPT_POST, 1);
           curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       }
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
       //添加请求头
       $headers = [
           'Authorization:'.$token,
           'Accept: application/json',
           'Content-Type: application/json; charset=utf-8',
           'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
       ];
       if(!empty($headers)){
           curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
       }
       $output = curl_exec($curl);
       curl_close($curl);
       return $output;
   }

   /**
    * @notes 敏感信息加解密
    */
   public static function getEncrypt($str,$config)
   {
       //$str是待加密字符串
       $public_key = file_get_contents($config['cert_path']);
       $encrypted = '';
       if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
           //base64编码
           $sign = base64_encode($encrypted);
       } else {
           throw new \Exception('encrypt failed');
       }
       return $sign;
   }

   /**
    * @notes 商家明细单号查询
    */
   public static function detailsQuery($withdrawApply,$config)
   {
       //请求URL
       $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$withdrawApply['batch_no'].'/details/out-detail-no/'.$withdrawApply['sn'];
       //请求方式
       $http_method = 'GET';
       //请求参数
       $data = [];
       $token  = self::token($url,$http_method,$data,$config);//获取token
       $result = self::https_request($url,$data,$token);//发送请求
       $result_arr = json_decode($result,true);
       return $result_arr;
   }
   function logout(){
    $uid=I('uid');
    M('users')->where('user_id={$uid}')->delete();
    $data=array();
   $data['status']=200;
  
   echo json_encode($data);
   }
   function gettask(){
   $uid=I('uid');
   $tabIndex=I('tabIndex');
   if($tabIndex==0){
   $list=M('goods')->where("store_id={$uid} and is_on_sale=1")->order("goods_id desc")->select(); 
   }else if($tabIndex==1) {
    $list=M('goods')->where("store_id={$uid} and is_on_sale=0") ->order("goods_id desc")->select();
   }else if($tabIndex==2) {
    $list=M('goods')->where("store_id={$uid} and is_on_sale=2" )->order("goods_id desc")->select();
   }
   foreach($list as $k => $v){
   $shenhe=M('order')->where("goods_id={$v['goods_id']} and order_status=1")->count(); 
   $yijing=M('order')->where("goods_id={$v['goods_id']} and order_status=2")->count();
   $count=M('order')->where("goods_id={$v['goods_id']} and order_status>-1")->count();
   $list[$k]['store_count']= $list[$k]['store_count']-$count;
   $list[$k]['shenhe']=$shenhe;
   $list[$k]['yijing']=$yijing;
   }
   $data=array();
   $data['status']=200;
   $data['list']=$list;
   echo json_encode($data);
   }
   public function getopenid(){

   }
   function jieshu(){
   $order=M('order')->where("order_status=1")->select(); 
   $time=time();
   foreach($order as $v){
   $good=M('goods')->where("goods_id={$v['goods_id']}")->find(); 
   $time1=$v['shipping_time']+86400;
   if($time1>$time){
    $data=array();
    $data['order_status']=2;
    M('order')->where("order_id={$v['order_id']}")->save($data);
    M('users')->where("user_id={$v['user_id']}")->setInc('user_money',$good['shop_price']);
   }
   }
   }
   public function returnrecharge(){
    $testxml = file_get_contents("php://input");
  // var_dump($xml);
 $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
//转成数组
$result = json_decode($jsonxml, true);
if($result){
//如果成功返回了
if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
 $orderid=$result['out_trade_no'];
 $recharge=M("goods")->where("order_sn={$orderid}")->find();
 
 if($recharge['is_on_sale']==0){

      $data=array();
      $data['pay_time']=time();
      //$data['is_on_sale']=1;
       $result=M("goods")->where("order_sn='{$orderid}'")->save($data);
  
 }else{
     
 }
}
}
}
function getorderinfo(){
    $id=I('id');
    $good=M('goods')->where("goods_id={$id}")->find();
    if($good['is_on_sale']==0){
    
    }
    }
    function tasksh(){
    $good=I('id');
    $order=M('order')->where("goods_id={$good}")->select();
    foreach($order as $k => $v){
        $good=M('goods')->where("goods_id={$v['goods_id']}")->find(); 
        $order[$k]['add_time']=date('Y-m-d H:i:s', $order[$k]['add_time']);  
        $order[$k]['shipping_time']=date('Y-m-d H:i:s', $order[$k]['shipping_time']);  
        $order[$k]['good']=$good;
    }
    $data=array();
    $data['status']=200;
    $data['list']=$order;
    echo json_encode($data);
}
function shenhedetail(){
 $order_id=I('id'); 
 $uid=I('uid');  
 $order=M('order')->where("order_id={$order_id}")->find();
 $user=M('users')->where("user_id={$order['user_id']}")->find();
 $good=M('goods')->where("goods_id={$order['goods_id']}")->find();
 $ordertj=M('ordertj')->where("order_id={$order_id}")->select();
 $fu=M('goodfu')->where("goods_id={$order['goods_id']}")->select();
 foreach($ordertj as $k => $v){
    $ordertj[$k]['name']=$fu[$k]['name']; 
 }
$yijing=M('order')->where("goods_id={$order['goods_id']} and order_status=2")->count();
$count=M('order')->where("goods_id={$order['goods_id']} and order_status=2")->count();
$sheng= $good['store_count']-$count;
$data=array();
$data['order']=$order;
$data['user']=$user;
$data['good']=$good;
$data['ordertj']=$ordertj;
$data['yijing']=$yijing;
$data['sheng']=$sheng;
$data1=array();
$data1['status']=200;
$data1['data']=$data;
echo json_encode($data1);
}
function subshnehe(){
$id=I('id');
$order=M('order')->where("order_id={$id}")->find();
$good=M('goods')->where("goods_id={$order['goods_id']}")->find();
$data=array();
$data['order_status']=2;
M('order')->where("order_id={$id}")->save($data);
$count=M('order')->where("goods_id={$order['goods_id']} and order_status=2")->count();
if($count==$good['store_count']){
    $data=array();
    $data['is_on_sale']=2;
    M('goods')->where("goods_id={$order['goods_id']}")->save($data);
}

M('users')->where("user_id={$order['user_id']}")->setInc('user_money',$good['shop_price']);
$data1=array();
$data1['status']=200;

echo json_encode($data1);
}
function subshnehe1(){
    $id=I('id');
    $order=M('order')->where("order_id={$id}")->find();
    $good=M('goods')->where("goods_id={$order['goods_id']}")->find();
    $data=array();
    $data['order_status']=-1;
    M('order')->where("order_id={$id}")->save($data);
  
  
    $data1=array();
    $data1['status']=200;
    
    echo json_encode($data1);
    }
   function getorderindex(){
       $uid=I('uid');
       $stype=I('stype');
       if($stype==0){
            $list=M('order')->where("user_id={$uid}")->select();  //all
       }else if($stype==1){
            $list=M('order')->where("user_id={$uid} and order_status=0")->select();//待审
       }else if($stype==2){
            $list=M('order')->where("user_id={$uid} and order_status=1")->select();//审核中
       }else if($stype==3){
            $list=M('order')->where("user_id={$uid} and order_status=3")->select();//已取消
       }else if($stype==4){
            $list=M('order')->where("user_id={$uid} and order_status=4")->select();//已完成
       }
       $time=time();
       foreach($list as $k => $v){
            $good=M('goods')->where("goods_id={$v['goods_id']}")->find();
            $list[$k]['add_time']=date('Y-m-d H:i:s', $list[$k]['add_time']);
            $list[$k]['good']=$good;
            if($v['order_status']==0){
            $list[$k]['subtime']=$list[$k]['tjendtime']-$time;
        }
       }
       $data=array();
       $data['status']=200;
       $data['list']=$list;
       echo json_encode($data);
   }
   
   function orderinfo(){
       $id=I('id');
       $uid=I('uid');
       $order=M('order')->where("order_id={$id}")->find();
       $good=M('goods')->where("goods_id={$order['goods_id']}")->find();
       $good['original_img']="http://renwu.tzhtc.net".$good['original_img'];
       $order['good']=$good;
       if($order['order_status']==0){
            $order['stype']=0;
       }else if($order['order_status']==3){
           $order['stype']=3;
       }else if($order['order_status']==4){
           $order['stype']=4;
       }
       
       $time=time();
       $order['subtime']=$order['tjendtime']-$time;
       $order['add_time']=date('Y-m-d H:i:s',$order['add_time']);
       $data=array();
       $data['status']=200;
       $data['order']=$order;
       echo json_encode($data);
   }
   function tjinfo(){
    $id=I('id');
    $uid=I('uid');
    $rwid=I('rwid');
    $good=M('goods')->where("goods_id={$rwid}")->find();
    $user=M('users')->where("user_id={$good['store_id']}")->find();
    $fu=M('goodfu')->where("goods_id={$rwid}")->select();
    foreach($fu as $k => $v){
     $fu[$k]['imgtj']=array();   
     $fu[$k]['imgurl']=explode('|',$fu[$k]['imgurl']); 
 
    
    }
    $order=M('order')->where("order_id={$id}")->find();
    $data=array();
    $data['status']=200;
    $data['good']=$good;
    $data['user']=$user;
    $data['fu']=$fu;
    $data['TaskOrder']=$order;
    echo json_encode($data);
   }
   //用户任务提交
   function rwtj(){
    $id=I('id');
    $fu=$_REQUEST['fu'];
    
    $orderInfo =  M('order')->where("order_id={$id}")->find();
    $goodsInfo = D("goods")->where(array("goods_id"=>$orderInfo["goods_id"]))->find();
//   echo $id;
    $fu=json_decode($fu,true);
    
    foreach($fu as $k => $v){
        $data=array();
        $data['order_id']=$id;
        $data['imgurl']=$v['imgurl'];   
        $data['img']=implode('|',$v['imgtj']);
        M('ordertj')->where(array("order_id"=>$id))->delete();
        M('ordertj')->add($data);
    }
    $data=array();
    $data['order_status']=1;
    $data['shipping_time']=time();
    $data["goods_price"]=$goodsInfo["shop_price"];
    M('order')->where("order_id={$id}")->save($data);
    $data=array();
    $data['status']=200;
    $data['good']=$good;
  
    echo json_encode($data);
   }
   function info(){
   $id=I('id');
   $uid=I('uid');
   $good=M('goods')->where("goods_id={$id}")->find();
   

   $list=M('goodfu')->where("goods_id={$id}")->select();
   foreach($list as $k => $v){
    $list[$k]['imgurl']=explode('|',$list[$k]['imgurl']); 
   }
   //var_dump($good);
   $user=M('users')->where("user_id={$uid}")->find();  
   $store=M('users')->where("user_id={$good['store_id']}")->find();  
   $kefu=M("config")->where("id=9")->find();
   if($good['is_on_sale']==2){
    $ifling=3;
   }else{
    $order=M('order')->where("goods_id={$id} and user_id={$uid}")->find();
    if($order){
    $ifling=1;
    }else{
    $ifling=0;
    }
   }
  
       $data=array();
       $data['status']=200;
       $data['good']=$good;
       $data['user']=$user;
       $data['list']=$list;
       $data['store']=$store;
       $data['kefu']=$kefu;
       $data['ifling']=$ifling;
   echo json_encode($data);
   
}
//领取任务
function lqrw(){
    $name=I('name');
    $id=I('oid');
    $price=I('price');
    $img=I('img');
    $uid=I('uid');
    $good=M('goods')->where("goods_id={$id}")->find();
    $time=time();
    $GoodsModel = new GoodsModel();
    //判断用户是否可以领取任务
    $checkGoods = $GoodsModel->checkRenwu($id,$uid);
    
    if(empty($checkGoods["status"])){
        echo json_encode($checkGoods,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);die();
    }
    if($good['subtime']=='2小时'){
        $time1=$time+60*60*2;
    }else{
        $time1=$time+60*60*3;
    }
    $data=array();
    $data['order_sn']=time().rand(1111,9999).$uid;
    $data['user_id']=$uid;
    $data['goods_id']=$id;
    $data['add_time']=$time;
    $data['tjendtime']=$time1;
    M('order')->add($data);
    M('goods')->where("goods_id={$id}")->save(array("surplus_count"=>$good["surplus_count"]+1));
    
    
    
    $store_count = $good["store_count"];
    $surplus_count = $good["store_count"];
    
    $data=array();
    $data['status']=200;
    echo json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
}
   function reg(){
    $mobile=I('mobile');
    $username=I('username');
    $password=I('password');
    $data=array();
    $data['mobile']=$mobile;
    $data['password']=md5($password);
    $user=M('users')->add($data);
    $data=array();
    $data['status']=200;
    echo json_encode($data);
   }
   function login(){
       $account=I('account');
       $password=I('password'); 
       $password=md5($password);
       $user=M('users')->where("mobile={$account} and password='{$password}'")->find();
       $user['token'] = md5(time().mt_rand(1,999999999));
        M('users')->where("user_id = {$user['user_id']}")->save(array('token'=>$user['token'],'last_login'=>time()));
        $result = array('status'=>1,'msg'=>'登陆成功','result'=>$user);
       $data=array();
       $data['status']=200;
       $data['userinfo']=$user;
       echo json_encode($data);
   }
   function getuser(){
    $user_id=I('uid');
    $user=M('users')->where("user_id={$user_id}")->find();
    
    
    $inc_type="withdraw_set";
    $withdraw_set=tpCache($inc_type);
    $data=array();
    $withdraw_outlay =$withdraw_set["withdraw_outlay"];//手续费
    $withdraw_min_money =$withdraw_set["withdraw_min_money"];//最小提现金额
    $withdraw_money =0;
    
    if(!empty($withdraw_outlay)){
        $outlay_money = ($user['user_money']*$withdraw_set["withdraw_outlay"])/100;
        $withdraw_money =$user['user_money']- $outlay_money;
        $withdraw_money = sprintf("%.2f", $withdraw_money);
        $data['withdraw_money']=$withdraw_money;//实际到账
        $data["withdraw_outlay"]=$withdraw_set["withdraw_outlay"];//提现手续费
        $data["withdraw_outlay_money"]=sprintf("%.2f", $outlay_money);//提现手续费
    }

    $data["withdraw_min_money"]=$withdraw_min_money;//提现手续费
    $data['status']=200;
    $data['user']=$user;
    echo json_encode($data);
   }
    /**
     * 分类列表显示
     */
    public function categoryList(){
        $this->display();
    }
    
    //文件上传
	function upload(){
        $url='';		
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        // $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
          $this->error($upload->getError());
        }else{// 上传成功
        // var_dump($info);
        $inc_type="shop_info";
        $shop_info=tpCache($inc_type);
        $host=$shop_info["host"];
        $path =$host."/Public/upload/";
        
        foreach($info as $file){
            $url=$path.$file['savepath'].$file['savename'];
        }
        
        $data=array();
        $data['status']=200;
         $data['url']=$url;
        echo json_encode($data);
    }	
}


   function uploadAvatar(){
         $url='';		
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        // $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
          $this->error($upload->getError());
        }else{// 上传成功
        // var_dump($info);
        $inc_type="shop_info";
        $shop_info=tpCache($inc_type);
        $host=$shop_info["host"];
        $path =$host."/Public/upload/";
        
        foreach($info as $file){
            $url=$path.$file['savepath'].$file['savename'];
        }
        }
        print_r($url);
    }





    function addrenwu(){
        $uid=I('uid');
        $bi=M('config')->where("id=2")->find();
        $bi=$bi['value'];//抽成比例1表示不抽
        $price=I('price');
        $price1=round($price*$bi,2);
        $maxcount = I("maxcount");
        $data=array();
        $data['store_id']=$uid;
        $data['goods_name']=I('name');
        $data['rwurl']=I('rwurl');
        $data['shop_price']=$price1;
        $data['market_price']=$price;
        $sum=$data['store_count']=I('sum');
        $overdue_time = $this->setOverdue_time(I('subtime'));
        $data['overdue_time']=$overdue_time;
        $data['endtime']=I('endtime');
        $data['subtime']=I('subtime');    
        $data['shetime']=I('shetime');
        $data["is_on_sale"]=0;
        $data['add_time']=time();        
        $data['type']=I('type');  
        $data["is_pay"]=0;
        $data["is_hot"]=1;
        $data["is_recommend"]=1;
        $data["is_new"]=1;
        $data["maxcount"]=!empty($maxcount)?$maxcount:1;
        $data["original_img"]=I("thumb");
        
        
        
        //任务添加判断
        $GoodsModel = new GoodsModel();
        $chackAddRenwu = $GoodsModel->chackAddRenwu($data);
        if(empty($chackAddRenwu["status"])){
            return $chackAddRenwu;
        }
        $buytype=I("buytype");
        $order_sn=$data['order_sn']=time().$uid.rand(1111,9999);
        $goodid=M('goods')->add($data);
        // var_dump($goodid);
        // die();
        if($goodid){
            $buzs=$_REQUEST['buzs'];
            $buzs=json_decode($buzs,true);
            $img1=0;
           
            foreach($buzs as $k => $v){
        
                $data=array();
                $data['name']=$v['name'];
                $img=implode('|',$v['img']);
                $data['imgurl']=$img;
                if($img&&$img1==0){
                    $img1=$img;  
                }
                $data['beizhu']=$v['imgtj'];
                $data['goods_id']= $goodid;
                M('goodfu')->add($data);   
                $data=array();
                if(empty(I("thumb"))){
                     $data['original_img']=$img1;
                }
                
                M('goods')->where("goods_id={$goodid}")->save($data);
            }
            
            
            $amount=$price*$sum;
            
            $total = floatval($amount);
            $total = round($total*100); // 将元转成分
            if(empty($total)){
                $total = 100;
            }
            $inc_type="shop_info";
            $shop_info=tpCache($inc_type);
            $host=$shop_info["host"];
            // 商品名称
            $subject = '任务支付';
            // 订单号，示例代码使用时间值作为唯一的订单ID号
            $out_trade_no =$order_sn;
            $return=[];
            if($buytype=="微信"){
                $url=$host."/wxpayv3/index.php?money=".$total."&out_trade_no=".$out_trade_no;
                $return=file_get_contents($url);
            }else if($buytype=="余额"){
                $userInfo = D("users")->where(array("user_id"=>$uid))->find();
                
     
                if($userInfo["user_money"]-$amount>=0){
                    $pay = new PayController();
                    $remake ="添加任务余额支付";
                    $return= $pay->balancePay($uid,$amount,$goodid,$remake,1,"renwu");
                    exit(json_encode($return,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));die();
                }else{
                    $data=array();
                    $data['status']=301;
                    $data['msg']="余额不足";
                    echo json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);die();
                }
                
                
                
                
                
            }
            
            
            
            echo $return;die();
        }else{
            $data=array();
            $data['status']=301;
            $data['msg']="信息错误";
            echo json_encode($data);  die(); 
        }
    }
    public  function  setOverdue_time($str){
        $strarray =explode("小时",$str);
        $num = $strarray[0];
        $time =  date('Y-m-d H:i:s', strtotime('+'.$num.'hour'));
        return $time;
    }
function getlist(){
  $tabBarsname=I('tabBarsname');
  if($tabBarsname=='全部'){
    $rows=M('goods')->where(array("goods_state"=>1))->select();
  }else{
    $rows=M('goods')->where("type='{$tabBarsname}' and goods_state=1")->order("goods_id desc")->limit(100)->select();
  }  
  foreach($rows as $k => $v){
    $rows[$k]['original_img']=$rows[$k]['original_img'];
  }
  $data=array();
    $data['status']=200;
    $data['rows']=$rows;
    echo json_encode($data);   
}
    /**
     * 模板列表
     */
    public function mobanlist(){
        $arr = glob("D:/wamp/www/svn_tpshop/mobile--html/*.html");
        foreach($arr as $key => $val)
        {
            $html = end(explode('/', $val));
            echo "<a href='http://www.php.com/svn_tpshop/mobile--html/{$html}' target='_blank'>{$html}</a> <br/>";            
        }        
    }
    
    /**
     * 商品列表页
     */
    public function goodsList(){
        $goodsLogic = new \Home\Logic\GoodsLogic(); // 前台商品操作逻辑类
        $id = I('get.id',0); // 当前分类id
        $lists = getCatGrandson($id);
        $this->assign('lists',$lists);
        $this->display();
    }
    
    public function ajaxGetMore(){
    	$p = I('p',1);
    	$favourite_goods = M('goods')->where("is_recommend=1 and is_on_sale=1  and goods_state = 1 ")->order('sort DESC')->page($p,10)->cache(true,TPSHOP_CACHE_TIME)->select();//首页推荐商品
    	$this->assign('favourite_goods',$favourite_goods);
    	$this->display();
    }

    /**
     * 店铺街
     * @author dyr
     * @time 2016/08/15
     */
    public function street()
    {
        $store_class = M('store_class')->where('')->select();
        $this->assign('store_class', $store_class);//店铺分类
        $this->display();
    }

    /**
     * ajax 获取店铺街
     */
    public function ajaxStreetList()
    {
        $p = I('p',1);
        $sc_id = I('get.sc_id','');
        $store_list = D('store')->getStreetList($sc_id,$p,10);
        foreach($store_list as $key=>$value){
            $store_list[$key]['goods_array'] = D('store')->getStoreGoods($value['store_id'],4);
        }
        $this->assign('store_list',$store_list);
        $this->display();
    }

    /**
     * 品牌街
     * @author dyr
     * @time 2016/08/15
     */
    public function brand()
    {
        $brand_model = M('brand');
        $brand_where['status'] = 0;
        $brand_class = $brand_model->field('cat_name')->group('cat_name')->order(array('sort'=>'desc','id'=>'asc'))->where($brand_where)->select();
        $brand_list = $brand_model->field('id,name,logo,url')->order(array('sort'=>'desc','id'=>'asc'))->where($brand_where)->select();
        $brand_count = count($brand_list);
        for ($i = 0; $i < $brand_count; $i++) {
            if (($i + 1) % 4 == 0) {
                $brand_list[$i]['brandLink'] = 'brandRightLink';
            } else {
                $brand_list[$i]['brandLink'] = 'brandLink';
            }
        }
        $this->assign('brand_list', $brand_list);//品牌列表
        $this->assign('brand_class', $brand_class);//品牌分类
        $this->display();
    }
    //获取公共配置
    public function getconfig(){
        $inc_type="basic";
        $basic=tpCache($inc_type);
        exit(json_encode(array("config"=>array("basic"=>$basic)),JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }
    
    
    
    
    
    
    
    
}